import 'dart:convert';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:magic_car/UI/Loading.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:image_picker/image_picker.dart';
import 'package:toast/toast.dart';
import 'dart:io';

class UpAskPage extends StatefulWidget {
  // final String oid;
  UpAskPage();

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<UpAskPage> {
  List formList;
  //final String oid;
  List imgs = new List();
  List img_url = new List();

  _MyHomePageState();
  TextEditingController _title = new TextEditingController();
  TextEditingController _content = new TextEditingController();
  FocusNode _contentFocusNode = FocusNode();
  initState() {
    super.initState();
    formList = [
      {
        "title": '里程表',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '车架号',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '车辆类型',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '车牌品牌车系',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '表里显程',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '排量（L/T）',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '发动机号',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '排放标准',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '国产进口',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '驱动形式',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
    ];
    imgs.add('resource/images/user/upimg.png');
    // loaddata();
  }

  //加载数据
  loaddata() async {
    Map<String, String> map = new Map();
   // map['oid'] = this.oid;
    //  SharedPreferences pref = await SharedPreferences.getInstance();
    //  map["id"]=pref.getString('uid');
    //  map["type"]="0";

    HttpHelper.post(HttpHelper.API_OrderDetail, (data) async {
      if (data != null) {
        if (data["code"].toString() == "1") {
          List oldlist = formList;
          var orderinfo = data["info"];
          for (var i = 0; i < oldlist.length; i++) {
            var item = oldlist[i];
            var str = "";
            if (i == 0)
              str = orderinfo["name"];
            else if (i == 1)
              str = orderinfo["phone_num"];
            else if (i == 2)
              str = orderinfo["name"];
            else if (i == 3)
              str = orderinfo["phone_num"];
            else if (i == 4)
              str = orderinfo["add_time"];
            else
              str = orderinfo["address"];

            item["sub_title"] = str;
          }

          setState(() {
            // formList = oldlist;
            // orders=data["info"];
          });
          //pref.setStringList('userinfo', data["info"]);

        }
      }
    }, params: map);
  }

  Widget buildcontent() {
    List<Widget> tiles = [];
    Widget content;
tiles.add(Padding(
        padding: new EdgeInsets.fromLTRB(10, 10, 10, 10),
        child: Container(
            height: 60,
            decoration: new BoxDecoration(
//背景
              color: Colors.white,
              //设置四周圆角 角度
              borderRadius: BorderRadius.all(Radius.circular(4.0)),
              //设置四周边框
            ),
            child: new Column(children: <Widget>[
              new Container(
                  height: 60,
                  child: new TextField(
                    //focusNode: _contentFocusNode,
                    controller: _title,
                    decoration: InputDecoration(
                        labelText: '请输入问题名称',
                        border: InputBorder.none,
                        contentPadding: EdgeInsets.all(10)),
                    maxLines: 10,
                  ))
            ]))));
    tiles.add(Padding(
        padding: new EdgeInsets.fromLTRB(10, 10, 10, 0),
        child: Container(
            height: 160,
            decoration: new BoxDecoration(
//背景
              color: Colors.white,
              //设置四周圆角 角度
              borderRadius: BorderRadius.all(Radius.circular(4.0)),
              //设置四周边框
            ),
            child: new Column(children: <Widget>[
              new Container(
                  height: 160,
                  child: new TextField(
                    //focusNode: _contentFocusNode,
                    controller: _content,
                    decoration: InputDecoration(
                        labelText: '请输入问题详情信息',
                        border: InputBorder.none,
                        contentPadding: EdgeInsets.all(10)),
                    maxLines: 10,
                  ))
            ]))));
    tiles.add(Padding(
        padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
        child: Container(
            width: double.infinity,
            // height: 160,
            decoration: new BoxDecoration(
//背景
              color: Colors.white,
              //设置四周圆角 角度
              borderRadius: BorderRadius.all(Radius.circular(4.0)),
              //设置四周边框
            ),
            // child: buildCImgs(),
            child: new Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[new Container(child: buildCImgs())])
                )));
    tiles.add(new Padding(
      padding: new EdgeInsets.all(20),
      child: SizedBox(
          width: double.infinity,
          height: 45,
          child: new RaisedButton.icon(
            icon: new Image.asset('resource/images/user/answer.png'),
            label: Text(
              '提交问题',
              style: TextStyle(fontSize: 15),
            ),
            color: Color.fromRGBO(278, 182, 251, 1),
            textColor: Colors.white,
            onPressed: () {
              //提交
              _contentFocusNode.unfocus();
              submit();
            },
          )),
    ));

    content = new Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  Widget buildCImgs() {
    List<Widget> tiles = [];

    Widget content;

    List items = imgs;
    // print('图片数组长度'+items.isNotEmpty.toString());
    if (items.length > 0) {
      // tiles.add(new Container(
      //       padding: new EdgeInsets.fromLTRB(60, 0, 20, 0),)
      for (var i = 0; i < items.length; i++) {
        //List temp1 = items[i] as List;
        tiles.add(new Container(
            padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
            child: Padding(
              padding: new EdgeInsets.fromLTRB(5, 0, 0, 10),
              child: GestureDetector(
                  onTap: () {
                    FocusScope.of(context).requestFocus(FocusNode()); //隐藏键盘
                    print('点击查看图片');
                    if (i == items.length - 1) {
                      getImage();
                    }
                    // Navigator.of(context).push(
                    //   NinePicture(items, i),
                    //);
                  },
                  child: i == items.length - 1
                      ? Image.asset('resource/images/user/upimg.png',
                          width: 100, height: 100)
                      : Image.network(items[i], width: 100, height: 100)),
            )));
      }
    }
    content = new Wrap(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

//选择图片
  getimgs(type) async {
    var image;
    if (type == 1) {
      image = await ImagePicker.pickImage(source: ImageSource.gallery);
    } else {
      image = await ImagePicker.pickImage(source: ImageSource.camera);
    }
    if (image == null) return;
    LoadingPage loadpage = new LoadingPage(context);
    loadpage.show();
    File _files = await FlutterNativeImage.compressImage(image.path);

    Map<String, String> map = new Map();

    HttpHelper.upLoadImage(_files, (data) {
      loadpage.close();
      print('data');
      if (data.containsKey('code')) {
        Toast.show(data['msg'], context);
      } else {
        imgs.removeLast();
        imgs.add(data["url"]);
        img_url.add(data["attachment"]);
        imgs.add('resource/images/user/upimg.png');
        setState(() {
          imgs = imgs;
        });
      }
    }, params: map);

    // if (_image == null) return;
    // Map<String, String> map = new Map();
    // HttpHelper.upLoadImage(_image, (data) {
    //   if(data.containsKey('code')){
    //     Toast.show(data['msg'], context);
    //   }else{
    //   setState(() {
    //     avatar = data['url'];
    //   });
    //   uploadAvatar();
    //   }
    // }, params: map);
  }

//选择图片方式
  Future getImage() async {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return new SimpleDialog(
            title: new Text('选择'),
            children: <Widget>[
              new SimpleDialogOption(
                child: new Text('相机'),
                onPressed: () {
                  Navigator.pop(context);
                  getimgs(0);
                },
              ),
              new SimpleDialogOption(
                child: new Text('相册'),
                onPressed: () {
                  Navigator.pop(context);
                  getimgs(1);
                },
              )
            ],
          );
        });
    // var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    // //_upLoadImage(image);//上传图片
    // setState(() {
    //   _image = image;
    // });
  }

  //提交答案
  submit() async {
    FocusScope.of(context).requestFocus(FocusNode());
    if (_content.text.trim().length == 0||_title.text.trim().length==0) {
      Toast.show('请输入内容', context);
      return;
    }
    var content = _content.text.trim();
    var title = _title.text.trim();
    //提交回答内容
    Map<String, String> map = new Map();
    var image_Str = "";
    for(var i=0;i<img_url.length;i++ ){
      var item = img_url[i];
      if(i==img_url.length-1){
       image_Str=image_Str+item;
      }else
       image_Str=image_Str+item+',';
    }

    //map["img"] = jsonEncode(img_url);
    map["img"]=image_Str;
    SharedPreferences pref = await SharedPreferences.getInstance();
    map["uid"] = pref.getString('uid');
   // map["id"] = this.oid;
    map["name"] = title;
    map["details"]=content;

    // map["page"]=page.toString();
    print(map);

    HttpHelper.post(HttpHelper.API_SubAsk,(data) async {
      if (data != null) {
        print(data);
        Toast.show(data["msg"], context);
        if (data["code"].toString() == "1") {
          Navigator.pop(context);
        }
      }
    }, params: map);
  }

  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text(
            '我要提问',
            style: TextStyle(color: Colors.black),
          ),
          backgroundColor: Colors.white,
          iconTheme: new IconThemeData(color: Colors.black),
          elevation: 0,
        ),
        body: new Center(
            child: Container(
          decoration: new BoxDecoration(
            color: Color.fromRGBO(238, 238, 238, 1),
          ),
          child: Padding(
              padding: new EdgeInsets.fromLTRB(0, 10, 0, 0),
              child: new ListView(
                children: <Widget>[buildcontent()],
              )),
        )));
  }
}
